import socket
import sys
import time

#create a tcp/ip socket
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

#bind the socket to the port.
server_name = socket.gethostname()
SERVERaddr = (server_name,10000)
print('开始连接于{}主机，端口{}'.format(*SERVERaddr))
sock.connect(SERVERaddr)
try:
    #发送消息
    message = b'this is a message.    It will be repeated.'

    print('sending {!r}'.format(message))
    sock.sendall(message)
    time.sleep(1)

    #‘盼望’返回的消息
    amount_recieved = 0
    amount_expected = len(message)

    while amount_recieved < amount_expected:
        data = sock.recv(16)
        amount_recieved += len(data)
        print('返回消息{!r}'.format(data))

finally:
    print('关闭连接（套接字）')
    sock.close()